
let wId = 0
class Watcher {
    constructor(update) {
        this.update = update
        this.id = wId++
        this.deps = []
        this.newDeps = []
        this.depsId = new Set()
        this.newDepsId = new Set()
        this.get()
    }

    get() {
        Dep.target = this
        this.update()
        this.cleanDep()
    }

    addDep(dep) {
        const id = dep.id
        if (!this.newDepsId.has(id)) {
            // 这次更新用到的dep
            this.newDepsId.add(id)
            this.newDeps.push(dep)
            // 确保不会重复添加
            if (!this.depsId.has(id)) {
                dep.addSub(this)
            }
        }
    }

    cleanDep() {
        // 清理上次dep依赖的watcher
        let i = this.deps.length
        while(i--) {
            let currentDep = this.depsp[i]
            if (!this.newDepsId.has(currentDep.id)) {
                currentDep.removeSub(this)
            }
        }

        let tmp = this.deps
        this.deps = this.newDeps
        this.newDeps = tmp
        this.newDeps = []
        
        tmp = this.depsId
        this.depsId = this.newDepsId
        this.newDepsId = tmp
        this.newDepsId.clear()
    }
}

window.Watcher = Watcher